﻿using System;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using ImageResizer;
using So.ImageResizer.Helpers;
using So.ImageResizer.Services;

namespace So.ImageResizer.Controllers {
    [HandleError]
    public class ImageResizerController : Controller {
        private readonly IImageResizerService _imageResizerService;

        public ImageResizerController(IImageResizerService imageResizerService) {
            _imageResizerService = imageResizerService;
        }

        /// <summary>
        /// Resizes given image and automatically caches the result for faster parsing
        /// </summary>
        /// <param name="url">Relative url</param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="maxWidth"></param>
        /// <param name="maxheight"></param>
        /// <param name="cropMode">None,Auto,Custom</param>
        /// <param name="scale"> </param>
        /// <param name="stretchMode"> </param>
        /// <returns></returns>
        public FilePathResult ResizedImage(string url, int width = 0, int height = 0, int maxWidth = 0, int maxheight = 0,
                                           CropMode cropMode = CropMode.Auto, ScaleMode scale = ScaleMode.Both, StretchMode stretchMode = StretchMode.Proportionally) {
            var settings = _imageResizerService.GetImageResizerSettings();
            string retValImageUrl;

            string ext = _imageResizerService.GetCleanFileExtension(url);
            if (!_imageResizerService.SupportedFileExtensions().Contains(ext)) {
                throw new ArgumentException("Invalid file extension! suported file extensions are: " + string.Join(",", _imageResizerService.SupportedFileExtensions()));
            }

            if (settings.ResizerHttpModuleEnabled) {
                var queryString = new QueryString()
                    .Add("format", ext)
                    .Add("width", width.ToString(CultureInfo.InvariantCulture))
                    .Add("height", height.ToString(CultureInfo.InvariantCulture))
                    .Add("cropMode", "auto");
                // .Add("scale", scale.ToString())
                //.Add("stretchMode", stretch.ToString());
                // ?format=png &width=220 &height=220 &crop=auto &rotate=90 &bgcolor=black &flip=h &borderWidth=5 &borderColor=gray &paddingWidth=10
                retValImageUrl = string.Concat(url, queryString);
                HttpContext.Response.Redirect(retValImageUrl);
            }
            else {
                retValImageUrl = _imageResizerService.ResizeImage(url, width, height, maxWidth, maxheight, cropMode, scale, stretchMode);
            }

            return new FilePathResult(retValImageUrl, _imageResizerService.GetMimeTypeByImageExtesion(ext));
        }
    }
}